package com.dk.hi.core;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Polygon;

/**
 * Represents a collision block
 */
public class Block {
	/**
	 * The block size
	 */
	public static final int SIZE = 32;

	/**
	 * Basic bounds of a block. It is a square of 31x31 pixels. The size is not exactly 32 for
	 * collision management
	 */
	private static final int[] BOUNDS = { 1, 1, 31, 1, 31, 31, 1, 31 };

	/**
	 * The block bounds
	 */
	private Polygon polygon;

	/**
	 * @param x
	 *            - x coordinate
	 * @param y
	 *            - y coordinate
	 */
	public Block(int x, int y) {
		this.polygon = new Polygon(new float[] { x + BOUNDS[0], y + BOUNDS[1], x + BOUNDS[2],
				y + BOUNDS[3], x + BOUNDS[4], y + BOUNDS[5], x + BOUNDS[6], y + BOUNDS[7] });
	}

	/**
	 * @param p
	 *            - A polygon
	 */
	public Block(Polygon p) {
		this.polygon = p;
	}

	/**
	 * Draws the polygon. For debug only!
	 * 
	 * @param g
	 *            - The canvas
	 */
	public void draw(Graphics g) {
		g.setColor(Color.red);
		g.draw(this.polygon);
	}

	/**
	 * @return the block's height
	 */
	public float getBlockHeight() {
		return this.polygon.getHeight();
	}

	/**
	 * @return the block's width
	 */
	public float getBlockWidth() {
		return this.polygon.getWidth();
	}

	/**
	 * @return the X coordinate of the block
	 */
	public float getBlockX() {
		return this.polygon.getX();
	}

	/**
	 * @return the Y coordinate of the block
	 */
	public float getBlockY() {
		return this.polygon.getY();
	}

	/**
	 * Tests if the block argument is in collision with the current block
	 * 
	 * @param b
	 *            - the block to test
	 * @return True if the 2 blocks are in collision
	 */
	public boolean collide(Block b) {
		if (b == null) {
			return false;
		} else if (b.polygon == null) {
			return false;
		} else if (b.polygon.intersects(this.polygon)) {
			return true;
		}
		return false;
	}

	/**
	 * Moves the block from coordinates.
	 * 
	 * @param dx
	 *            - x delta
	 * @param dy
	 *            - y delta
	 */
	public void moveBlock(float dx, float dy) {
		this.polygon.setX(this.polygon.getX() + dx);
		this.polygon.setY(this.polygon.getY() + dy);
	}

	/**
	 * Initializes the block origin.
	 * 
	 * @param x
	 *            - x coordinate
	 * @param y
	 *            - y coordinate
	 */
	public void setBlockOrigin(float x, float y) {
		this.polygon.setX(x);
		this.polygon.setY(y);
	}
}
